function [y,TotalBits] = jpg2KQuantize(x,NL,CompNo)
% [y,TotalBits] = jpg2KQuantize(x,NL,CompNo)
% Quantizes using JPEG2000 scalar quantization rule
% Input:
% x = cell array containing the 2D DWT coefficients
% NL = number of levels of octave-band 2D DWT
% CompNo = Component number, which can be 1, 2, or 3
% 1 for Y, 2 for y1 (Cb) and 3 for y2 (Cr)
% Output:
% y = cell array of the same size as x containing
% quantized DWT coefficients
% TotalBits = Total bits used up by the coefficients
%
% The input cell array x{1,2:4}contains the 1HL, 1LH, and 1HH
% DWT coefficients at level 1, etc., and x{NL,1:4}
% contains the LL, HL, LH, and HH coefficients at level NL.
%
% The quantization step sizes are usually specified in the
% headers of the bit stream. However, here, we simply
% assign the number of bits for the uniform quantizers
% and compute the appropriate quantization steps.
%
y = cell(NL,4);% output cell array
maxVal = zeros(4,1);% maximum coefficient value
%minVal = zeros(4,1);
Qstep = zeros(NL,4);% array to store the quantization steps
Qbits = zeros(NL,4);% array to store the quantizer bits
switch CompNo
case 1
Qstep(1,2:3)=(2^(8-0))*(1+8/(2^11));
Qstep(1,4)=(2^(8-0))*(1+8/(2^11));
Qstep(2,2:3)=(2^(8-3))*(1+8/(2^11));
Qstep(2,4)=(2^(8-2))*(1+8/(2^11));
Qstep(2,4) = Qstep(2,4)/0.731668; % uses CSF
Qstep(3,2:3)=(2^(8-5))*(1+8/(2^11));
Qstep(3,2:3) = Qstep(3,2:3)/0.564344; % uses CSF
Qstep(3,4)=(2^(8-5))*(1+8/(2^11));
Qstep(3,4)= Qstep(3,4)/0.285968; % uses CSF
Qstep(3,1)=(2^(8-5))*(1+8/(2^11));
case{2,3}
Qstep(1,2:3)=(2^(8-0))*(1+8/(2^11));
Qstep(1,4)=(2^(8-1))*(1+8/(2^11));
Qstep(2,2:3)=(2^(8-3))*(1+8/(2^11));
Qstep(2,4)=(2^(8-2))*(1+8/(2^11));
Qstep(3,2:3)=(2^(8-4))*(1+8/(2^11));
Qstep(3,4)=(2^(8-3))*(1+8/(2^11));
Qstep(3,1)=(2^(8-5))*(1+8/(2^11));
end
TotalBits = 0;
for n = 1:NL
if n<NL
m1=2;
else
m1=1;
end
for m = m1:4
maxVal(m) = max(x{n,m}(:));
t = round(log2(maxVal(m)/Qstep(n,m)));
if t<0
Qbits(n,m)= 0;
else
Qbits(n,m)= t;
end
TotalBits = TotalBits+Qbits(n,m)*size(x{n,m},1)*size(x{n,m},2);
end
end
%
for n = 1:NL
if n<NL
m1=2;
else
m1=1;
end
for m = m1:4
s = sign(x{n,m});
q2 = Qstep(n,m)/2;
y{n,m}= s .* round(abs(x{n,m})/q2)*q2;
end
end



